package com.sqs.interceptor;

import com.sqs.constant.ExceptionConstant;
import com.sqs.constant.RateLimiterConstant;
import com.sqs.exception.RequestTooQuickException;
import com.sqs.limiter.IpRateLimiter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.List;

@Component
public class PublicApiRateLimiterInterceptor implements HandlerInterceptor {

    @Autowired
    private IpRateLimiter ipRateLimiter;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String path = request.getRequestURI();
        // 限流key可以自定义（比如接口路径、IP+路径）
        String ip = request.getRemoteAddr();
        String key = ip + ":" + path;
        boolean allowed = ipRateLimiter.tryAcquire(key, RateLimiterConstant.RATE_LIMIT_QPS);
        if (!allowed) {
            throw new RequestTooQuickException(ExceptionConstant.REQUEST_TOO_QUICK);
        }
        return true; // 放行
    }

}
